import cgi, sys

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

from sqlalchemy import *
from sqlalchemy.orm import sessionmaker

from model import President, SpeechCategory, SpeechText, Party
from upload import upload_dataset

import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger( 'Main' )

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write('<html><body>')
    query = Party.all()
    results = query.fetch(2)
    for p in results:
    	log.debug(str(p.id)+' - '+p.name)
    	self.response.out.write(str(p.id)+' - '+p.name+'<br/>')
    self.response.out.write('<br/>')    	
    query = President.all()
    results = query.fetch(5)
    for p in results:
    	log.debug(str(p.id)+' - '+p.name)
    	self.response.out.write(str(p.id)+' - '+p.name+' '+p.party.name+'<br/>')

    self.response.out.write("</body></html>")
    
    
class ExtDbTest(webapp.RequestHandler):
    def get(self):
        db_engine = create_engine('postgres://postgres:postgres@localhost/galaxy_demo1')    
        db_engine.echo = True  
        metadata = MetaData(db_engine)
        session = sessionmaker(bind=db_engine)
        request_table = Table('request', self.metadata, autoload=True )
        query = select(columns=[request_table.c.name])
        results = query.execute().fetchall()[0]
        log.debug('RESULTS: '+str(results))
        
                
application = webapp.WSGIApplication([('/', MainPage)],
                                     [('/psql', ExtDbTest)],
                                     debug=True)

def main():
    log.debug(str(sys.argv))
    log.debug('Uploading datasets...')
    upload_dataset()
    run_wsgi_app(application)

if __name__ == "__main__":
  main()
